package com.cff.springbootwork.mongodb.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cff.springbootwork.mongodb.model.User;
import com.cff.springbootwork.mongodb.service.UserAddationService;

@RestController
@RequestMapping("/mongo2")
public class MongodbAddationRest {
	@Autowired
	UserAddationService userService;

	@PostMapping("/save")
	public String saveObj(@RequestBody User user) {
		return userService.save(user);
	}

	@GetMapping("/findAll")
	public List<User> findAll() {
		return userService.findAll();
	}

	@GetMapping("/findOne")
	public User findOne(@RequestParam Long id) {
		return userService.getUserById(id);
	}

	@GetMapping("/findOneByName")
	public User findOneByName(@RequestParam String name) {
		return userService.getUserByName(name);
	}

	@PostMapping("/update")
	public String update(@RequestBody User user) {
		User existUser = userService.getUserById(user.getId());
		if (existUser == null) {
			existUser = user;
		} else {
			if (user.getAge() != null) {
				existUser.setAge(user.getAge());
			}

			if (user.getPassword() != null) {
				existUser.setPassword(user.getPassword());
			}

			if (user.getName() != null) {
				existUser.setName(user.getName());
			}

			if (user.getPhone() != null) {
				existUser.setPhone(user.getPhone());
			}

			if (user.getRegisterTime() != null) {
				existUser.setRegisterTime(user.getRegisterTime());
			}

			if (user.getUsername() != null) {
				existUser.setUsername(user.getUsername());
			}
		}

		return userService.update(existUser);
	}

	@PostMapping("/delOne")
	public String delOne(@RequestBody User user) {
		return userService.deleteUser(user);
	}
}
